<template>
	<div>
		<el-breadcrumb separator="/">
			<el-breadcrumb-item><i class="el-icon-s-home" style="margin-right: 15px;font-size: 16px"></i>记录校核</el-breadcrumb-item>
    </el-breadcrumb>
		<div class="info">
			<el-card shadow="always">
        <div slot="header">
          <el-form :model="queryParams" ref="equipInfoForm" label-width="80px" size="small">
            <el-row>
              <el-col :span="8">
                <el-form-item label="委试号">
                  <el-input placeholder="请输入委试号" v-model="queryParams.orderNum" clearable style="width:100%"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="试验员">
                  <el-input placeholder="请输入试验员" v-model="queryParams.userName" clearable style="width:100%"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="审核状态">
                  <el-select v-model="queryParams.status" placeholder="请选择审核状态" style="width:100%" clearable>
                    <el-option label="所有" value="all"></el-option>
                    <el-option label="待审核" value="0"></el-option>
                    <el-option label="已通过" value="1"></el-option>
                    <el-option label="已驳回" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>						
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="试验日期">
                  <el-date-picker v-model="queryParams.timeSelect" type="daterange" align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd" style="width:100%"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="16" style="text-align: right;">
                <div style="padding-left: 20px;">
                  <el-button type="primary" size="small" @click="getRecordList">查询</el-button>
                  <el-button size="small" class="textBtn" @click="resetInfor">重置</el-button>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </div>
				<el-table  @sort-change='sortChange' v-loading="dataLoading" :data="testRecordData.slice((currentPage-1)*pagesize,currentPage*pagesize)" row-key="instr_id" ref="testRecordData" stripe style="width: 100%;">
          <el-table-column sortable="custom" prop="test_number" label="委试号" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column sortable="custom" prop="prod_name" label="试品名称" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column sortable="custom" prop="nickname" align="center" label="试验员"></el-table-column>
          <el-table-column sortable="custom" prop="end_time" align="center" label="试验日期"></el-table-column>
          <el-table-column sortable="custom" prop="review_user" align="center" label="审核人"></el-table-column>
          <el-table-column sortable="custom" label="审核状态" align="center">
            <template slot-scope="scope">
              <div :style="{'color':(scope.row.review_status === '待审核' ?'#5bd89b':(scope.row.review_status === '已通过'?'#6c59dd':'#f55366'))}">{{scope.row.review_status}}</div>
            </template>
          </el-table-column>
					<el-table-column label="操作" align="center">
						<template slot-scope="scope">
							<el-button type="text" :disabled="btnList.view" @click="viewInfo(scope.$index, scope.row)" style="color: #6665E5;" size="small">预览</el-button>
							<el-button type="text" v-if="scope.row.review_status === '待审核'" :disabled="btnList.reject" @click="checkInfo(scope.$index, scope.row)" style="color: #6665E5;" size="small">审核通过</el-button>
              <el-button type="text" v-if="scope.row.review_status === '待审核'" :disabled="btnList.reject" @click="rejectInfo(scope.$index, scope.row)" style="color: #6665E5;" size="small">审核驳回</el-button>
            </template>
					</el-table-column>
				</el-table>
				<el-pagination class="pagination" background :hide-on-single-page="showPagination" :current-page.sync="currentPage" @size-change="handleSizeChange" :page-size="pagesize" layout="prev, pager, next" :total="testRecordData.length"></el-pagination>
			</el-card>
      <el-dialog title="温馨提示" :visible.sync="dialogVisible" width="30%">
        <div style="text-align: center;font-size:16px">是否确定通过审核?</div>
        <span slot="footer" class="dialog-footer">
        <el-button class="textBtn" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updatePassAudit">确 定</el-button></span>
      </el-dialog>
      <el-dialog title="温馨提示" :visible.sync="rejectVisible" width="30%">
        <div style="text-align: center;font-size:16px">是否确定驳回审核?</div>
        <span slot="footer" class="dialog-footer">
        <el-button class="textBtn" @click="rejectVisible = false">取 消</el-button>
        <el-button type="primary" @click="updatePassAudit">确 定</el-button></span>
      </el-dialog>
		</div>
	</div>
</template>

<script>
import { serverURL } from '../../public/setting';
import sessionStorage from '../../public/storage.js';
import roleBtn from '../../public/means.js';
import { base64 } from '../../public/base64';
import dayjs from 'dayjs';
export default {
	data() {
		return {
      // sortRule:{prop:null,order:null},
			btnList: {
				view: false, // 预览
        reject: true // 审核驳回或通过
      },
      auditSign: '', // 审核结果标记
      dialogVisible: false,
      rejectVisible: false, // 驳回审核弹窗
      reviewId: '', // 确认审核的id
      testRecordData: [], // 测试记录表格数据
      testRecordDatas: [], // 测试记录表格数据
      allTestRecord: [], // 所有测试记录
      menuId: 15,
			queryParams: {
				orderNum: '', // 委试号
				userName: '', // 试验员
				status: 'all', // 审核状态
      	timeSelect: '',	// 时间选择
			},
			dataLoading: false,	// 数据加载
			showPagination: true,
			currentPage: 1,
      pagesize: 8,
			pickerOptions: {
				shortcuts: [{
					text: '最近一周',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
						picker.$emit('pick', [start, end]);
					}
					}, {
						text: '最近一个月',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
							picker.$emit('pick', [start, end]);
						}
					}, {
						text: '最近三个月',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
							picker.$emit('pick', [start, end]);
						}
				}]
			},
		};
	},
	methods: {
    // 表格数据排序通用函数
		generalSort(attr, rev){
			//第一个参数传入表示排的是哪一列，第二个参数是升还是降排序
			if (rev == undefined) {
				rev = 1;
			} else {
				rev = (rev) ? 1 : -1;
			}
			return function (arry, barry) {
				arry = arry[attr];
				barry = barry[attr];
				if (arry < barry) {
					return rev * -1;
				}
				if (arry > barry) {
					return rev * 1;
				}
				return 0;
			}
		},
    // // 表格排序问题
		// sortChange(column){
		// 	this.currentPage = 1;
		// 	if (column.prop === 'test_number') {
		// 		this.testRecordData = this.testRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
		// 	}
    //   else if (column.prop === 'prod_name') {
    //     this.testRecordData = this.testRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
    //   }
    //   else if (column.prop === 'nickname') {
    //     this.testRecordData = this.testRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
    //   }
    //   else if (column.prop === 'end_time') {
    //     this.testRecordData = this.testRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
    //   }
    //   else if (column.prop === 'review_user') {
    //     this.testRecordData = this.testRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
    //   }
		// 	this.testRecordData = this.testRecordData.slice(0, this.pageSize) // 排序完显示到第一页
		// },
    sortChange(column){
		// console.log(column,"sortchange")
	　　　　//点击向上【向下】激发排序　　
		this.currentPage = 1;
		// this.sortRule.order = column.order;
		// this.sortRule.prop = column.prop;
		if(column.order !== null && column.prop !== null){   //项目中要求所有列可排序，所以条件进行了判断！==null 即所有列 【如果项目中只有单个列【特定列】存在排序要求，出现混乱，colum.prop == "列的key"即可。】
			let index = column.prop;
			let data = [];
			let datas = [];
			for(let i = 0; i < this.testRecordData.length; i++){  //this.tableDate 为表格总数据，后台请求的数据
				if(this.testRecordData[i][index] === null){
					data.push(this.testRecordData[i]);
				}else{
					datas.unshift(this.testRecordData[i]);
				}
			}
			datas.sort(this.generalSort(column.prop, column.order === 'ascending'))
			console.log(datas);
			this.testRecordData = datas.concat(data)
			// this.trialRecordData = this.trialRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
		}
	　　//再点击向上【向下】恢复原始排序
		if(column.order === null){
			this.testRecordData = this.testRecordDatas;
		}
    	},
    //  重置筛选条件信息
    resetInfor(){
      this.queryParams.orderNum ='';
      this.queryParams.userName ='';
      this.queryParams.status = 'all';
      this.setTimeDef();
      // this.testRecordData = JSON.parse(JSON.stringify(this.allTestRecord));
    },
    handleSizeChange(val) {
      this.pagesize=val;
		},
    // 预览
    viewInfo(index,row){
      // console.log('row',row);
      const viewPath = row.file_path.substring(0,row.file_path.lastIndexOf(".")+1); //获取文件名称
      // console.log(5555555555,viewPath);
      const url = serverURL + viewPath + 'pdf';
      window.open(url)
      // window.open('http://123.56.132.202:8012/onlinePreview?url='+encodeURIComponent(base64.encode(url)));
    },
    // 再次确认是否审核通过
    checkInfo (index,row) {
      this.dialogVisible = true;
      this.reviewId = row.review_id;
      this.auditSign = 'pass';
    },
    // 再次确认是否驳回审核
    rejectInfo (index,row) {
      this.rejectVisible = true;
      this.reviewId = row.review_id;
      this.auditSign = 'reject';
    },
    // 确认审核通过
    async updatePassAudit(){
      const params = {
        auditSign: this.auditSign,
        reviewId: this.reviewId,
        userId:JSON.parse(sessionStorage.getItem('userInfo')).user_id,
      }
      const ret = await this.$http.post("/testRecord/updatePassAudit",params);
      if (ret.code === 200) {
        this.$message.success('审核成功');
        this.getRecordList();
        this.dialogVisible = false;
        this.rejectVisible = false;
      }
    },
    //  设置默认时间为1个月
    setTimeDef () {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      const startTime = dayjs(start).format('YYYY-MM-DD');
      const endTime = dayjs(end).format('YYYY-MM-DD');
      this.queryParams.timeSelect = [startTime, endTime];
    },
    // 根据筛选条件查询测试记录（暂不使用）
    queryRecord(){
      this.dataLoading = true;
      this.testRecordData = [];
      if (this.queryParams.status !== '所有') { // 查询条件多审核状态
        this.allTestRecord.map((item) => {
          if (item.test_number.indexOf(this.queryParams.orderNum) !== -1 && item.nickname.indexOf(this.queryParams.userName) !== -1 && item.review_status.indexOf(this.queryParams.status) !== -1) {
            this.testRecordData.push(item);
          }
        });
      } else {
        this.allTestRecord.map((item) => {
          if (item.test_number.indexOf(this.queryParams.orderNum) !== -1 && item.nickname.indexOf(this.queryParams.userName) !== -1) {
            this.testRecordData.push(item);
          }
        });
      }
      if (this.queryParams.timeSelect !== null && this.queryParams.timeSelect !== '') {
        const startTime = dayjs(this.queryParams.timeSelect[0]).valueOf();
        const endTime = dayjs(this.queryParams.timeSelect[1]).valueOf();
        this.testRecordData = this.testRecordData.filter((item) => {
          const date = dayjs(item.alarm_time).valueOf();
          return startTime <= date && date <= endTime
        })
      }
      this.dataLoading = false;
    },
		// 获取审核记录表数据
		async getRecordList(){
      this.dataLoading = true;
      if(this.queryParams.timeSelect === null){
        this.queryParams.timeSelect = '';
      }
      const params = {
        startTime: this.queryParams.timeSelect[0],
        endTime: this.queryParams.timeSelect[1],
        userName: this.queryParams.userName,
        status: this.queryParams.status,
        orderNum: this.queryParams.orderNum
      }
			const ret = await this.$http.get("/testRecord/getAuditRecordList",{params});
      // this.allTestRecord = JSON.parse(JSON.stringify(ret.result));
			this.testRecordData = ret.result;
			this.testRecordDatas = ret.result;
			this.dataLoading = false;
		},
    // 按钮权限状态
		async roleBtnList () {
      const role_id = JSON.parse(sessionStorage.getItem('userInfo')).role_id;
      if(role_id){
        // 获取按钮权限状态
        let arr = await roleBtn.roleBtnList(role_id, this.menuId);
        this.btnList = arr;
      }
    }
	},
	created() {
    this.roleBtnList()
  },
	mounted() {
    this.setTimeDef();
    this.getRecordList();
	}
};
</script>
<style lang="scss" scoped>
@import "./RecordAudit.scss";
</style>